using System;
using System.Collections.Generic;
using Volo.Abp.Domain.Entities.Auditing;

namespace CKY.AgentPlatform.Domain.McpTools;

/// <summary>
/// MCP工具类型枚举
/// </summary>
public enum McpToolType
{
    /// <summary>
    /// 文件操作
    /// </summary>
    FileSystem = 0,
    
    /// <summary>
    /// 网络请求
    /// </summary>
    Http = 1,
    
    /// <summary>
    /// 数据库操作
    /// </summary>
    Database = 2,
    
    /// <summary>
    /// 代码执行
    /// </summary>
    CodeExecution = 3,
    
    /// <summary>
    /// 搜索工具
    /// </summary>
    Search = 4,
    
    /// <summary>
    /// 计算工具
    /// </summary>
    Calculator = 5,
    
    /// <summary>
    /// 数据处理
    /// </summary>
    DataProcessing = 6,
    
    /// <summary>
    /// API集成
    /// </summary>
    ApiIntegration = 7,
    
    /// <summary>
    /// 资源访问
    /// </summary>
    Resource = 8,
    
    /// <summary>
    /// 自定义工具
    /// </summary>
    Custom = 99
}

/// <summary>
/// 工具状态枚举
/// </summary>
public enum McpToolStatus
{
    /// <summary>
    /// 未配置
    /// </summary>
    NotConfigured = 0,
    
    /// <summary>
    /// 已配置
    /// </summary>
    Configured = 1,
    
    /// <summary>
    /// 运行中
    /// </summary>
    Running = 2,
    
    /// <summary>
    /// 已停止
    /// </summary>
    Stopped = 3,
    
    /// <summary>
    /// 错误
    /// </summary>
    Error = 4
}

/// <summary>
/// MCP工具参数定义
/// </summary>
public class McpToolParameter
{
    /// <summary>
    /// 参数名称
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 参数描述
    /// </summary>
    public string Description { get; set; }

    /// <summary>
    /// 参数类型
    /// </summary>
    public string Type { get; set; }

    /// <summary>
    /// 是否必需
    /// </summary>
    public bool IsRequired { get; set; }

    /// <summary>
    /// 默认值
    /// </summary>
    public object DefaultValue { get; set; }

    /// <summary>
    /// 参数示例
    /// </summary>
    public object Example { get; set; }

    /// <summary>
    /// 验证规则
    /// </summary>
    public string ValidationRules { get; set; }

    public McpToolParameter()
    {
        Type = "string";
        IsRequired = true;
        ValidationRules = "";
    }
}

/// <summary>
/// MCP工具执行结果
/// </summary>
public class McpToolExecutionResult
{
    /// <summary>
    /// 是否成功
    /// </summary>
    public bool IsSuccess { get; set; }

    /// <summary>
    /// 结果数据
    /// </summary>
    public object Data { get; set; }
    /// <summary>
    /// 执行结果
    /// </summary>
    public object Result { get; set; }

    /// <summary>
    /// 错误信息
    /// </summary>
    public string ErrorMessage { get; set; }

    /// <summary>
    /// 执行时间（毫秒）
    /// </summary>
    public int ExecutionTimeMs { get; set; }

    /// <summary>
    /// 输出日志
    /// </summary>
    public string Logs { get; set; }

    public McpToolExecutionResult()
    {
        IsSuccess = false;
        ErrorMessage = "";
        Logs = "";
    }
}

/// <summary>
/// MCP工具实体 - Model Context Protocol工具管理
/// </summary>
public class McpTool : AuditedAggregateRoot<Guid>
{
    /// <summary>
    /// 工具名称
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 工具描述
    /// </summary>
    public string Description { get; set; }

    /// <summary>
    /// 工具类型
    /// </summary>
    public McpToolType ToolType { get; set; }

    /// <summary>
    /// 工具版本
    /// </summary>
    public string Version { get; set; }

    /// <summary>
    /// 工具状态
    /// </summary>
    public McpToolStatus Status { get; set; }

    /// <summary>
    /// 命令/脚本
    /// </summary>
    public string Command { get; set; }

    /// <summary>
    /// 工具配置（JSON格式）
    /// </summary>
    public string Configuration { get; set; }

    /// <summary>
    /// 参数定义（JSON格式）
    /// </summary>
    public string Parameters { get; set; }

    /// <summary>
    /// 返回格式定义（JSON格式）
    /// </summary>
    public string ReturnFormat { get; set; }

    /// <summary>
    /// 是否激活
    /// </summary>
    public bool IsActive { get; set; }

    /// <summary>
    /// 执行超时时间（秒）
    /// </summary>
    public int TimeoutSeconds { get; set; }

    /// <summary>
    /// 最大重试次数
    /// </summary>
    public int MaxRetries { get; set; }

    /// <summary>
    /// 权限要求
    /// </summary>
    public string RequiredPermissions { get; set; }

    /// <summary>
    /// 安全等级（1-5，5为最高）
    /// </summary>
    public int SecurityLevel { get; set; }

    /// <summary>
    /// 使用次数统计
    /// </summary>
    public int UsageCount { get; set; }

    /// <summary>
    /// 成功次数统计
    /// </summary>
    public int SuccessCount { get; set; }

    /// <summary>
    /// 失败次数统计
    /// </summary>
    public int FailureCount { get; set; }

    /// <summary>
    /// 平均执行时间（毫秒）
    /// </summary>
    public double AverageExecutionTimeMs { get; set; }

    /// <summary>
    /// 最后执行时间
    /// </summary>
    public DateTime? LastExecutedAt { get; set; }

    /// <summary>
    /// 标签
    /// </summary>
    public string Tags { get; set; }

    /// <summary>
    /// 作者信息
    /// </summary>
    public string Author { get; set; }

    /// <summary>
    /// 文档链接
    /// </summary>
    public string DocumentationUrl { get; set; }

    /// <summary>
    /// 元数据（JSON格式）
    /// </summary>
    public string Metadata { get; set; }

    /// <summary>
    /// MCP服务器ID
    /// </summary>
    public Guid? McpServerId { get; set; }

    /// <summary>
    /// 函数名称（用于本地函数类型）
    /// </summary>
    public string FunctionName { get; set; }

    /// <summary>
    /// API端点（用于HTTP API类型）
    /// </summary>
    public string ApiEndpoint { get; set; }

    /// <summary>
    /// HTTP方法（用于HTTP API类型）
    /// </summary>
    public string HttpMethod { get; set; }

    /// <summary>
    /// HTTP头（用于HTTP API类型）
    /// </summary>
    public string Headers { get; set; }

    /// <summary>
    /// 脚本类型（用于脚本类型）
    /// </summary>
    public string ScriptType { get; set; }

    /// <summary>
    /// 脚本内容（用于脚本类型）
    /// </summary>
    public string ScriptContent { get; set; }

    protected McpTool()
    {
        // EF Core requires parameterless constructor
    }

    /// <summary>
    /// 创建新的MCP工具实例
    /// </summary>
    /// <param name="id">工具ID</param>
    /// <param name="name">工具名称</param>
    /// <param name="description">工具描述</param>
    /// <param name="toolType">工具类型</param>
    /// <param name="command">命令/脚本</param>
    public McpTool(
        Guid id,
        string name,
        string description,
        McpToolType toolType,
        string command) : base(id)
    {
        Name = name;
        Description = description;
        ToolType = toolType;
        Version = "1.0.0";
        Status = McpToolStatus.NotConfigured;
        Command = command;
        Configuration = "{}";
        Parameters = "[]";
        ReturnFormat = "{}";
        IsActive = true;
        TimeoutSeconds = 30;
        MaxRetries = 3;
        RequiredPermissions = "";
        SecurityLevel = 1;
        UsageCount = 0;
        SuccessCount = 0;
        FailureCount = 0;
        AverageExecutionTimeMs = 0;
        Tags = "";
        Author = "";
        DocumentationUrl = "";
        Metadata = "{}";
        FunctionName = "";
        ApiEndpoint = "";
        HttpMethod = "GET";
        Headers = "{}";
        ScriptType = "";
        ScriptContent = "";
    }

    /// <summary>
    /// 获取工具参数列表
    /// </summary>
    /// <returns>参数列表</returns>
    public List<McpToolParameter> GetParameters()
    {
        try
        {
            if (string.IsNullOrWhiteSpace(Parameters))
                return new List<McpToolParameter>();

            return System.Text.Json.JsonSerializer.Deserialize<List<McpToolParameter>>(Parameters)
                   ?? new List<McpToolParameter>();
        }
        catch
        {
            return new List<McpToolParameter>();
        }
    }

    /// <summary>
    /// 验证工具配置
    /// </summary>
    /// <returns>验证结果</returns>
    public (bool isValid, List<string> errors) ValidateConfiguration()
    {
        var errors = new List<string>();

        if (string.IsNullOrWhiteSpace(Name))
            errors.Add("工具名称不能为空");

        if (string.IsNullOrWhiteSpace(Command))
            errors.Add("工具命令不能为空");

        if (TimeoutSeconds <= 0)
            errors.Add("超时时间必须大于0");

        if (SecurityLevel < 1 || SecurityLevel > 5)
            errors.Add("安全等级必须在1-5之间");

        // 验证必需参数
        var parameters = GetParameters();
        foreach (var param in parameters.Where(p => p.IsRequired))
        {
            if (string.IsNullOrWhiteSpace(param.Name))
                errors.Add($"必需参数名称不能为空");
        }

        return (errors.Count == 0, errors);
    }

    /// <summary>
    /// 更新执行统计
    /// </summary>
    /// <param name="isSuccess">是否成功</param>
    /// <param name="executionTimeMs">执行时间</param>
    public void UpdateExecutionStats(bool isSuccess, int executionTimeMs)
    {
        UsageCount++;
        LastExecutedAt = DateTime.UtcNow;

        if (isSuccess)
        {
            SuccessCount++;
        }
        else
        {
            FailureCount++;
        }

        // 更新平均执行时间
        AverageExecutionTimeMs = (AverageExecutionTimeMs * (UsageCount - 1) + executionTimeMs) / UsageCount;
    }

    /// <summary>
    /// 获取成功率
    /// </summary>
    /// <returns>成功率（0-1）</returns>
    public double GetSuccessRate()
    {
        if (UsageCount == 0)
            return 1.0;

        return (double)SuccessCount / UsageCount;
    }

    /// <summary>
    /// 检查工具是否可以执行
    /// </summary>
    /// <param name="userPermissions">用户权限列表</param>
    /// <returns>是否可以执行</returns>
    public bool CanExecute(List<string> userPermissions = null)
    {
        if (!IsActive || Status != McpToolStatus.Configured)
            return false;

        if (string.IsNullOrWhiteSpace(RequiredPermissions))
            return true;

        if (userPermissions == null || userPermissions.Count == 0)
            return false;

        var requiredPerms = RequiredPermissions.Split(',', StringSplitOptions.RemoveEmptyEntries)
            .Select(p => p.Trim())
            .ToList();

        return requiredPerms.All(rp => userPermissions.Contains(rp));
    }

    /// <summary>
    /// 设置工具状态
    /// </summary>
    /// <param name="status">新状态</param>
    public void SetStatus(McpToolStatus status)
    {
        Status = status;
    }

    /// <summary>
    /// 更新配置
    /// </summary>
    /// <param name="configuration">配置JSON字符串</param>
    public void UpdateConfiguration(string configuration)
    {
        Configuration = configuration ?? "{}";
        Status = McpToolStatus.Configured;
    }

    /// <summary>
    /// 更新标签
    /// </summary>
    /// <param name="tags">标签字符串，逗号分隔</param>
    public void UpdateTags(string tags)
    {
        Tags = tags ?? "";
    }

    /// <summary>
    /// 重置统计信息
    /// </summary>
    public void ResetStats()
    {
        UsageCount = 0;
        SuccessCount = 0;
        FailureCount = 0;
        AverageExecutionTimeMs = 0;
        LastExecutedAt = null;
    }

    /// <summary>
    /// 获取工具摘要信息
    /// </summary>
    /// <returns>摘要信息</returns>
    public string GetSummary()
    {
        return $"{Name} ({ToolType}) - {Description}";
    }

    /// <summary>
    /// 检查工具是否需要配置
    /// </summary>
    /// <returns>是否需要配置</returns>
    public bool NeedsConfiguration()
    {
        return Status == McpToolStatus.NotConfigured || Status == McpToolStatus.Error;
    }
}